import moment from 'moment';
import { queryDevRepairs, expDevRepairs, queryDevRepairDet, devUnbind } from '../services/api';

function method(str, a, b) {
  let type = 'string';
  if (str === 'updateTime') {
    type = 'date';
  } else if (str === 'progId') {
    type = 'num';
  }
  switch (type) {
    case 'num': // 数字排序
      return a - b;
    case 'date': // 日期排序，IE8下'2012-12-12'这种格式无法设置时间，替换成'/'
      return moment(a).unix() - moment(b).unix();
    default:
      // 字符串排序
      return a.localeCompare(b);
  }
}
export default {
  namespace: 'devfix',

  state: {
    list: [],
    detail: '',
    pagination: {
      current: 1,
      pageSize: 10,
    },
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryDevRepairs, payload);
      let dataSource = response.devRepairs;
      if (payload.sorter) {
        const s = payload.sorter.split('_');
        if (s[1] === 'descend') {
          dataSource = dataSource.sort((prev, next) => method(s[0], next[s[0]], prev[s[0]]));
        } else {
          dataSource = dataSource.sort((prev, next) => method(s[0], prev[s[0]], next[s[0]]));
        }
      }

      let pageSize = 10;
      if (payload.pageSize) {
        pageSize = payload.pageSize * 1;
      }

      const result = {
        list: Array.isArray(response.devRepairs) ? dataSource : [],
        pagination: {
          total: response.pageInfo.pageTotal,
          pageSize,
          current: parseInt(payload.page, 10) || 1,
        },
      };

      //console.log('log', result);
      yield put({
        type: 'save',
        payload: result,
      });
    },
    *export({ payload, callback }, { call, put }) {
      const response = yield call(expDevRepairs, payload);
      // console.log('response', response);
      if (response?.expDevRepairs?.expFileUrl) callback(response.expDevRepairs.expFileUrl);
    },
    *devunbind({ payload, callback }, { call, put }) {
      const response = yield call(devUnbind, payload);
      // console.log('response', response);
      if (response?.devUnbind) callback();
    },
    *fetchdetail({ payload, callback }, { call, put }) {
      const response = yield call(queryDevRepairDet, payload);
      const result = response.devRepairDet;
      //console.log('log', result);
      yield put({
        type: 'savedetail',
        payload: result,
      });
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        list: action.payload.list,
        pagination: action.payload.pagination,
      };
    },
    savedetail(state, action) {
      return {
        ...state,
        detail: action.payload.result,
      };
    },
  },
};
